/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-10 11:51:46
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-04-03 09:00:30
 * @Description:
 */
import { Application } from "egg";

// import { WorkerEmitEvent } from "../../ws";
/**
 *接收的ws消息进行封装处理。
 *
 * @export
 * @class OnMessage
 */
export default class OnMessage {
  data: any;
  app: Application;
  wsuid: string;
  event: string;

  /**
   * Creates an instance of OnMessage.
   * 接收的ws消息进行预封装处理。
   * @param {*} data
   * @param {*} app
   * @memberof OnMessage
   */
  constructor(data, app) {
    this.wsuid = data.wsuid;
    this.event = data.event;
    this.data = data;
    this.app = app;
  }

  /** 给某个wsuid回复响应信息。通常用于先接收再回复。 */
  response(data) {
    this.app.messenger.sendToAgent("ws-response", {
      wsuid: this.wsuid,
      event: this.event,
      data,
    });
  }

  /** response的别名 */
  res(data) {
    this.response(data);
  }

  /** 广播给所有连接 */
  broadcast(data) {
    this.app.messenger.sendToAgent("ws-broadcast", {
      wsuid: this.wsuid,
      event: this.event,
      data,
    });
  }

  /** 广播给同房间的人 */
  sendRoom(data) {
    this.app.messenger.sendToAgent("ws-room", {
      wsuid: this.wsuid,
      event: this.event,
      data,
    });
  }

  /** 专门向某一个或多个wsuid发送信息。 */
  send(wsuids: string | string[], data) {
    if (typeof wsuids === "string") {
      wsuids = [wsuids];
    }
    // console.log(wsuids, data);
    if (Array.isArray(wsuids)) {
      this.app.messenger.sendToAgent("ws-send", {
        wsuids: wsuids,
        wsuid: this.wsuid,
        event: this.event,
        data,
      });
    }
  }

  /** 封装的可统一调用上面的发送信息的方法event即为方法名 */
  // emit(
  //   event: WorkerEmitEvent,
  //   ...args: [data: any] | [wsuids: string, data: any]
  // ) {
  //   if (this[event]) {
  //     this[event](...args);
  //   }
  // }
}
